package com.example.com.netty.handle;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

/**
 * @author 杜豪波
 * @description: TODO
 * @date 2020/1/3 15:38
 */
public class NettyUDPHandler extends ChannelInboundHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(NettyUDPHandler.class);
    // Netty4服务器名称
    private String serviceName;

    /**
     * @function 构造函数
     */
    public NettyUDPHandler() {
        super();
    }
    /**
     * @function 构造函数
     */
    public NettyUDPHandler(String serviceName) {
        this.serviceName = serviceName;
    }

    /**
     * @author clq
     * @function 接收处理
     * @date 2019-06-10
     */
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet)
            throws Exception {
        InetSocketAddress sender = packet.sender();
        logger.debug(serviceName + ",UDP信道来源 "  + sender.getHostString() + ":" + sender.getPort());

        // 读取收到的数据
        ByteBuf byteBuf = (ByteBuf) packet.copy().content();
        byte[] byteArray = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(byteArray);
        String body = new String(byteArray, CharsetUtil.UTF_8);
        logger.debug(serviceName + ",UDP信道收到服务端的数据：" + body);

        //数据统一处理
    }

    /**
     * @author clq
     * @function 异常处理
     * @date 2019-06-10
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.debug(serviceName + ",UDP信道连接异常,信道编号:" + ctx.channel().id() + "\n");
        logger.debug(cause.getMessage());
        ctx.channel().close();
    }

}
